package org.yuedu.service;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
import org.jboss.logging.Logger;
import org.yuedu.entity.User;
import org.yuedu.util.JwtUtil;

@ApplicationScoped
public class AuthService {

    @Inject
    Logger logger;

    public String authenticate(String email, String password) {
        User user = User.findByEmail(email);
        logger.info("password:" + hashPassword(password) + " user.passwordHash:" + user.passwordHash);
        if (hashPassword(password).equals(user.passwordHash)) {
            return JwtUtil.generateToken(email, user.id.intValue()); // 将Long类型转换为Integer类型
        } else {
            throw new RuntimeException("Invalid credentials");
        }
    }

    @Transactional
    public User register(String email, String password) {
        User existingUser = User.findByEmail(email);
        if (existingUser != null) {
            throw new RuntimeException("Email already registered!");
        } else {
            User newUser = new User();
            newUser.email = email;
            newUser.passwordHash = "123";
            newUser.persistAndFlush();
            return newUser;
        }
    }

    // 将 password 哈希后和数据库中存储的哈希结果比较
    private boolean checkPassword(String password, String hashedPassword) {
        logger.info("Checking password: " + password + " hashPassword: " + hashPassword(password));
        // 简单实现，实际项目中应使用BCrypt等安全的密码哈希算法
        return password.equals(hashPassword(password));
    }

    private String hashPassword(String password) {
        // 简单实现，实际项目中应使用BCrypt等安全的密码哈希算法
        // 这里仅为演示目的
        return "hashed_" + password;
    }
}